const express = require('express')
const validate = require('express-validation')
const _ = require('lodash')
const config = require('./config')
const tokenChecker = require('../../util/tokenChecker')
const validation = require('../../util/validation')

const goodRouter = express.Router()

const constructFunc = (func) => {
  return async (req, res, next) => {
    try {
      func(req, res, next)
    } catch (e) {
      next(e)
    }
  }
}

_.forIn(config, (value, key) => {
  const method = key
  const apiObj = value
  _.forIn(apiObj, (value, url) => {
    const { isTokenChecker, isValidate, func } = value
    const tc = isTokenChecker ? tokenChecker : () => true
    if (method === 'get') {
      goodRouter.get(url, tc, constructFunc(func))
    } else goodRouter.post(url, tc, constructFunc(func))
  })
})
